<script setup lang="ts">
import {ref, h, reactive} from 'vue'
import SearchButtonGroup from '@components/SearchButtonGroup';
import DataTableAction from '@components/DataTable/src/components/DataTableAction';


import {
  FormInst, NImage,
  NPopconfirm,
  NSwitch,
  SelectOption,
  useMessage
} from 'naive-ui';
import {imagePreview, permsJudg} from '@/util';
import {delRequest, postPutRequest} from '@/api/data'
import DataTable from '@components/DataTable'
import {AddSharp} from "@vicons/material";



import ImageSelection from "@components/ImageSelection";

const message = useMessage()


const searchParam = ref({
  name: null,
  status: null,
})
const statusOptions = ref<SelectOption[]>([
  {
    label: '启用',
    value: 0,
  }, {
    label: '禁用',
    value: 1,
  }
])
//数据表
const data_list = ref<any>();
const columns = ref([
  {
    title: '名称',
    key: 'name',
    width: 230,
  }, {
    title: '图片',
    key: 'img',
    width: 100,
    render(row: { img: string }) {
      if (row.img) {
        return h(NImage, {
          width: 20,
          height: 20,
          src: imagePreview(row.img)
        })
      }
    }
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center',
    render(row: { id: number, status: number }) {
      return h(NSwitch, {
        round: false,
        checkedValue: 0,
        uncheckedValue: 1,
        value: row.status,
        onUpdateValue: function (value) {
          if (permsJudg('wmethod:up:status')) { //权限 有权限进行一下操作
            row.status = value;
            postPutRequest('w_method/up_status', {
              id: row.id,
              status: value
            }, 'PUT').then((result: ResponseResult) => {
              message.create(result.message, {
                type: result.code === 200 ? 'success' : 'error',
                duration: 1500,
              });
              row.status = result.code === 200 ? value : value ? 0 : 1;
            })
          }
        }
      })
    }
  }, {
    title: '排序',
    key: 'sort',
    width: 100,
  }, {
    title: '添加时间',
    key: 'createTime',
    minWidth: 175,
  }
]);
//操作列
const actionColumn = reactive({
  width:110,
  title: "操作",
  key: "action",
  fixed: "right",
  render(record: Recordable) {
    return h(DataTableAction, {
      actions: [
        {
          label: '修改',
          type: 'primary',
          onClick: handleEdit.bind(null, record),
          permission: ['wmethod:edit']
        },
        {
          label: '删除',
          type: 'error',
          popConfirm: NPopconfirm,
          onPositiveClick: handleDelete.bind(null, record),
          confirm: {
            text: '确定删除当前提现方式吗？',
          },
          disabled: !!record.isDisabled,
          permission: ['wmethod:del']
        },
      ]
    });
  },
});

//新增、修改数据表单
const addEditModel = ref<boolean>(false);
const addEditFormRef = ref<FormInst | null>(null);
const handelSubmitLoading = ref<boolean>(false);

const addEditForm = ref({
  id: 0,
  name: <null | string>null,
  img: <null | string>null,
  status: 0,
  sort: 100,
})
const addEditFormRules = ref({
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请填写提现方式名称'
  }
})
//查询
const handleSubmitSearch = () => {
  data_list.value.searchListData();
}
//修改
const handleEdit = (record: Recordable) => {
  addEditForm.value.id = record.id;
  addEditForm.value.name = record.name;
  addEditForm.value.img = record.img;
  addEditForm.value.status = record.status;
  addEditForm.value.sort = record.sort;
  addEditModel.value=true;
}
//删除
const handleDelete = (record: Recordable) => {
  delRequest('w_method/del', record.id).then((result: ResponseResult) => {
    if (result.status === 0 && result.code === 200) {
      message.success(result.message, {
        duration: 1500,
        onLeave() {
          data_list.value.reload();
        }
      })
    } else {
      message.error(result.message);
    }
  })
}
//关闭新增、修改模态框
const closeAddEditModel = () => {
  addEditForm.value.id = 0;
  addEditForm.value.name = null;
  addEditForm.value.img = null;
  addEditForm.value.status = 0;
  addEditForm.value.sort = 100;
  handelSubmitLoading.value = false;
}
//提交新增、修改数据
const handelSubmitData = (e: MouseEvent) => {
  e.preventDefault();
  addEditFormRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      const url = addEditForm.value.id ? 'w_method/edit' : 'w_method/add';
      postPutRequest(url, addEditForm.value, addEditForm.value.id ? 'PUT' : 'POST').then((result: ResponseResult) => {
        if (result.code === 200) {
          message.success(result.message, {
            duration: 1500,
            onLeave() {
              addEditModel.value = false;
              if (addEditForm.value.id) {
                data_list.value.reload();
              } else {
                data_list.value.searchListData();
              }
            }
          })
        } else {
          message.error(result.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
</script>

<template>
  <n-card :bordered="false">
    <n-alert type="warning" class="alert_small m-b-10">
      温馨提示：状态蓝色为启用、灰色为禁用状态。
    </n-alert>
    <n-alert :show-icon="false" class="m-b-10">
      <n-form :model="searchParam" class="search-forms"
              inline
              :show-feedback="false"
              label-placement="left"
              @keydown.enter.prevent="handleSubmitSearch">
        <n-form-item label="名称">
          <n-input v-model:value="searchParam.name" placeholder="请输入关键字查询" clearable/>
        </n-form-item>
        <n-form-item label="状态">
          <n-select v-model:value="searchParam.status" :options="statusOptions" placeholder="请选择状态" style="width:120px"
                    clearable/>
        </n-form-item>
        <n-form-item>
          <search-button-group @submit="handleSubmitSearch"
                               @reset="()=>(searchParam.name=null,searchParam.status=null)"/>
        </n-form-item>
      </n-form>
    </n-alert>
    <data-table ref="data_list" :columns="columns"
                :action-column="actionColumn"
                :row-key="(row:Recordable) => row.id"
                :params="searchParam"
                list-url="w_method/list"
                default-serial-number
                serial-number-title="序号">
      <template #toolbarLeft>
        <n-button type="success" v-permission="['wmethod:add']" @click="()=>(addEditModel=true)">
          <n-icon :size="18">
            <AddSharp/>
          </n-icon>
          新增
        </n-button>
      </template>
    </data-table>
  </n-card>
  <!--  新增、修改数据  -->
  <n-modal v-model:show="addEditModel"
           :title="addEditForm.id?'修改提现方式':'新增提现方式'" :mask-closable="false"
           :show-icon="false" preset="dialog" @after-leave="closeAddEditModel">
    <n-form ref="addEditFormRef" :model="addEditForm" :rules="addEditFormRules" require-mark-placement="left"
            label-width="auto" label-placement="left">
      <n-form-item label="名称" path="name">
        <n-input v-model:value="addEditForm.name" placeholder="提现方式名称" clearable/>
      </n-form-item>
      <n-form-item label="图片" path="img">
        <image-selection v-model:value="addEditForm.img"/>
      </n-form-item>
      <n-form-item label="状态" path="status">
        <n-switch :round="false" v-model:value="addEditForm.status" :checked-value="0" :unchecked-value="1">
          <template #checked>
            启用
          </template>
          <template #unchecked>
            禁用
          </template>
        </n-switch>
      </n-form-item>
      <n-form-item label="排序" path="sort">
        <n-input-number v-model:value="addEditForm.sort" :show-button="false" placeholder="排序" clearable/>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button @click="()=>(addEditModel=false)">取消</n-button>
        <n-button type="primary" :loading="handelSubmitLoading" @click="handelSubmitData">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<style scoped lang="scss">

</style>